package com.bkitmobile.kesu.android.GUI;

import java.util.Vector;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bkitmobile.kesu.android.ClassInfo.StoreMessage;
import com.bkitmobile.kesu.android.connectServer.staticClass;

public class ChatActivity extends Activity implements OnClickListener, OnKeyListener{
	public static final int CHAT_HANDLE = -2;
	public static final int CLOSE_HANDLE = -1;
	public static boolean isStated = false;

	private ScrollView contentChat;
	private Button btnSend;
	private ImageButton btnClose, btnMore;
	private EditText txtInput;
	private LinearLayout currentContainer;
	private TextView titlebar;
	private Vector<LinearLayout> listLayoutContainer;
	private Vector<String> listChatter;
	private Bundle extra;
	private int intCurrentChat;
	private boolean isChangedOwner = false;
	private Builder more;
	private Handler mHandler;
	
	private class Layout extends LinearLayout
	{
		public Layout(Context context, AttributeSet attrs) {
			super(context, attrs);
			// TODO Auto-generated constructor stub
		}
		public Layout(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
		}
		public void addView (View child) 
		{
			super.addView(child);
			mHandler.sendEmptyMessage(-1);
			
		}
		
	}
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.chat_main);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
		
		staticClass.isChat = true;
		listLayoutContainer  = new Vector<LinearLayout>();
		listChatter = new Vector<String>();
		
		
		txtInput = (EditText) findViewById(R.id.chat_input);
		btnSend = (Button) findViewById(R.id.chat_btnSend);
		btnClose = (ImageButton) findViewById(R.id.chat_btnClose);
		btnMore = (ImageButton) findViewById(R.id.chat_btnMore);
		titlebar = (TextView) findViewById(R.id.custom_title);
		
		contentChat = (ScrollView) findViewById(R.id.chat_contentChat);
		LinearLayout ll = new LinearLayout(this);
		ll.addView(new Button(this));
		ll.addView(new Button(this), 0);
		ll.setOrientation(LinearLayout.VERTICAL);
		contentChat.addView(ll);
		btnSend.setOnClickListener(this);
		btnMore.setOnClickListener(this);
		btnClose.setOnClickListener(this);
		txtInput.setOnClickListener(this);
		txtInput.setOnKeyListener(this);
		extra = getIntent().getExtras();
		more = new AlertDialog.Builder(this);
		more.setTitle("More");
		
		mHandler=new Handler(){
			public void handleMessage(android.os.Message msg)
			{
				contentChat.fullScroll(ScrollView.FOCUS_DOWN);
			}
		};
		staticClass.chatHandler = new Handler(){
			public void handleMessage(android.os.Message msg)
			{
				super.handleMessage(msg);
				String owner = msg.getData().getString("owner");
				String message = msg.getData().getString("message");
				int pos = getPosOfChatterInList(owner);
				if (pos < 0) 
				{
					newChatter(owner);
					pos = getPosOfChatterInList(owner);
				}
				receiveMess(owner, message, listLayoutContainer.get(pos));
			}
		};
		int size = extra.getInt("size");
		for (int i = 0 ; i < size ; i++)
		{
			StoreMessage stored = (StoreMessage) extra.getSerializable("user"+i);
			setChatter(stored.getId());
			int sized = stored.getMessage().size();
			for (int j = 0 ; j < sized ; j++)
			{
				try{
				newMess(stored.getMessage().get(j).getOwner()
						, stored.getMessage().get(j).getMessage(),true);
				} catch (Exception e)
				{
					Log.d("size",sized+","+j);
				}
			}
		}
		String chatter = extra.getString("chatter");
		setChatter(chatter);
		
		
		
	}
	
	public void onResume() {
		super.onResume();
		String chatter = extra.getString("chatter");
		setChatter(chatter);
	}
	
	private void newChatter(String chatter){
		listChatter.add(chatter);
		currentContainer = new Layout(this);
		currentContainer.setOrientation(LinearLayout.VERTICAL);
		listLayoutContainer.add(currentContainer);
		contentChat.removeAllViews();
		contentChat.addView(currentContainer);
		TextView tmp = new TextView(this);
		tmp.setText("\n");
		currentContainer.addView(tmp);
		if (staticClass.isActived.size() > 0 )staticClass.isActived.remove(0);
		staticClass.isActived.add(chatter);
	}
	
	private void resumeChat(int pos){
		System.out.println("resume");
		if(pos == intCurrentChat)
			return;
		intCurrentChat = pos;
		
		subResumeChat(pos);
	}

	private void subResumeChat(int pos) {
		titlebar.setText(listChatter.get(pos).toString() + " | Chat - KeSu");
		Log.d("Resume chat", listChatter.get(pos).toString());
		currentContainer = (LinearLayout) listLayoutContainer.get(pos);
		if (staticClass.isActived.size() > 0 ) 
			staticClass.isActived.remove(0);
		staticClass.isActived.add(listChatter.get(pos));
		contentChat.removeAllViews();
		contentChat.addView(currentContainer);
	}
	
	private void setChatter(String chatter){
		
		if(chatter == null){
			//TODO: getString from network
		}
		if(chatter == null)
			return;
		int pos = getPosOfChatterInList(chatter);
		titlebar.setText(chatter + " | Chat - KeSu");
		if(pos < listChatter.size()){
			//TODO: open old chat
			resumeChat(pos);
		}
		else{
			intCurrentChat = pos;
			newChatter(chatter);
		}
		
		
	}
	public void receiveMess(String strOwner, String strMess,LinearLayout frame){
		
		final TextView owner = new TextView(this);
		owner.setText(strOwner+":");
		owner.setTypeface(Typeface.MONOSPACE, Typeface.BOLD);
		owner.setTextColor(Color.WHITE);
		owner.setPadding(0, 5, 0, 0);
		final TextView mess = new TextView(this);
		mess.setText(strMess);
		mess.setPadding(10, 0, 0, 0);
		if(isChangedOwner)
			try{
				currentContainer.addView(owner);
			}catch (Exception e) {
				// TODO: handle exception
			}
			frame.addView(owner);
			frame.addView(mess);
	}	
	public void newMess(String strOwner, String strMess,boolean load){
		
		final TextView owner = new TextView(this);
		owner.setText(strOwner+":");
		owner.setTypeface(Typeface.MONOSPACE, Typeface.BOLD);
		owner.setTextColor(Color.WHITE);
		owner.setPadding(0, 5, 0, 0);
		final TextView txtMess = new TextView(this);
		txtMess.setText(strMess);
		txtMess.setPadding(10, 0, 0, 0);
		if(isChangedOwner)
			try{
				currentContainer.addView(owner);
			}catch (Exception e) {
				// TODO: handle exception
			}
		currentContainer.addView(owner);
		currentContainer.addView(txtMess);
		isStated = true;
		if (!load)
		{
			Message mess = new Message();
			Bundle bundle = new Bundle();
			bundle.putString("owner", (String) listChatter.get(intCurrentChat));
			bundle.putString("message", strMess);
			mess.setData(bundle);
			mess.what = CHAT_HANDLE;
			staticClass.sendToService.sendMessage(mess);
			staticClass.socket.println("<chat><dest>"+listChatter.get(intCurrentChat)+"<message>"+strMess);
		}
	}
	
	private void close(){
		System.out.println(intCurrentChat);
		/*listChatter.remove(intCurrentChat);
		listLayoutContainer.remove(intCurrentChat);*/
		Message mess = new Message();
		Bundle bundle = new Bundle();
		
		
		mess.what = CLOSE_HANDLE;
		mess.setData(bundle);
		
		if(listChatter.size() == 1)
		{
			staticClass.isChat = false;
			bundle.putString("user", listChatter.get(intCurrentChat).toString());
			listChatter.remove(intCurrentChat);
			listLayoutContainer.remove(intCurrentChat);
			isStated = false;
			
			staticClass.sendToService.sendMessage(mess);
			this.finish();
		}
		else{
			int saved = intCurrentChat;
			if(intCurrentChat == listChatter.size() - 1){
				intCurrentChat--;
				subResumeChat(intCurrentChat);
			}
				
			else{
				subResumeChat(intCurrentChat+1);
			}
			
			bundle.putString("user", listChatter.get(saved).toString());
			listChatter.remove(saved);
			listLayoutContainer.remove(saved);
			
			staticClass.sendToService.sendMessage(mess);
		}
		
		System.out.println(intCurrentChat);
	}
	
	private int getPosOfChatterInList(String chatter){
		int size = listChatter.size();
		for(int i = 0; i < size; i++)
			if(chatter.equals(listChatter.get(i)))
				return i;
		return size;
	}
	private void selectChatter(int pos){
		resumeChat(pos);
	}

	@Override
	public void onClick(View v) {
		if(v == btnSend || v == txtInput){
			String strMess = txtInput.getText().toString().trim();
			txtInput.setText(null);	
			if (strMess.equals("")) 			
				return;
			newMess("me", strMess,false);
		}
		else if(v == btnMore){
			int size = listChatter.size();
			CharSequence []arrChatter = new CharSequence[size];
			for(int i = 0; i < size; i++){
				arrChatter[i] = (CharSequence) listChatter.get(i);
				Log.d("List chatter", (String) arrChatter[i]);
			}
				
			more.setItems(arrChatter, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					selectChatter(which);
				}
			});
			more.show();
		}
		else if(v == btnClose){
			close();
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (staticClass.isActived.size() > 0 )staticClass.isActived.remove(0);
		super.onDestroy();
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		
		if(event.getAction() == KeyEvent.ACTION_DOWN){
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				staticClass.isChat = false;
				finish();
				break;
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_ENTER:
            	String strMess = txtInput.getText().toString().trim();
    			txtInput.setText(null);	
    			if (strMess.equals("")) 			
    				return false;
    			newMess("me", strMess,false);
    			
                return false;
			}
		}
		return false;
	}
	
	
}


 